package myJs.api

import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import shared.pojo.Pojo._
import sttp.client3.UriContext
import upickle.default._

import scala.concurrent.Future

/**
 * Created by yz on 7/11/2022
 */
object AdminApi {

  val baseUrl = s"${Api.apiUrl}/liveForest/admin"

  def getAllUser = {
    val url = s"${baseUrl}/getAllUser"
    Api.preparseRequest[List[ujson.Obj]]
      .get(uri"${url}")
      .send(Api.sttpBackend)
      .map(_.body)
      .flatMap(Future.fromTry)
  }

  def getUserById(id:String) = {
    val url = s"${baseUrl}/getUserById"
    Api.preparseRequest[UserData]
      .get(uri"${url}?id=${id}")
      .send(Api.sttpBackend)
      .map(_.body)
      .flatMap(Future.fromTry)
  }

  def updateUser(request:UserData) = {
    val url = s"${baseUrl}/updateUser"
    Api.preparseRequest[ValidData]
      .post(uri"${url}")
      .body(write(request))
      .send(Api.sttpBackend)
      .map(_.body)
      .flatMap(Future.fromTry)
  }

  def addDays(request:UserData) = {
    val url = s"${baseUrl}/addDays"
    Api.preparseRequest[ValidData]
      .post(uri"${url}")
      .body(write(request))
      .send(Api.sttpBackend)
      .map(_.body)
      .flatMap(Future.fromTry)
  }

  def deleteUserById(request:IdData) = {
    val url = s"${baseUrl}/deleteUserById"
    Api.preparseRequest[ValidData]
      .delete(uri"${url}")
      .body(write(request))
      .send(Api.sttpBackend)
      .map(_.body)
      .flatMap(Future.fromTry)
  }

  def detailInfo = {
    val url = s"${baseUrl}/detailInfo"
    Api.preparseRequest[AdminData]
      .get(uri"${url}")
      .send(Api.sttpBackend)
      .map(_.body)
      .flatMap(Future.fromTry)
  }

  def changePassword(request:ChangePassword.Request) = {
    val url = s"${baseUrl}/changePassword"
    Api.preparseRequest[ValidData]
      .post(uri"${url}")
      .body(write(request))
      .send(Api.sttpBackend)
      .map(_.body)
      .flatMap(Future.fromTry)
  }

  def changeEmail(request: ChangeEmail.Request) = {
    val url = s"${baseUrl}/changeEmail"
    Api.preparseRequest[ValidData]
      .post(uri"${url}")
      .body(write(request))
      .send(Api.sttpBackend)
      .map(_.body)
      .flatMap(Future.fromTry)
  }


}
